import pandas as pd
from matplotlib import pyplot as plt

def cal_huanbi():
    fpath = "../datas/beijing_tianqi/beijing_tianqi_2017-2019.csv"
    df = pd.read_csv(fpath, index_col="ymd", parse_dates=True)
    # 替换掉温度的后缀℃
    df["bWendu"] = df["bWendu"].str.replace("℃", "").astype('int32')
    df["yWendu"] = df["yWendu"].str.replace("℃", "").astype('int32')
    # 新的df，为每个月的平均最高温
    df = df[["bWendu"]].resample("M").mean()
    print(df)
    print("-----------------------------------")
    # 将索引按照日期升序排列
    df.sort_index(ascending=True,inplace=True)
    df.plot()
    plt.show()

    # 方法1：pandas.Series.pct_change
    # pct_change方法直接算好了"(新-旧)/旧"的百分比
    df["bWendu_way1_huanbi"] = df["bWendu"].pct_change(periods=1)
    df["bWendu_way1_tongbi"] = df["bWendu"].pct_change(periods=12)
    # print(df)
    # 方法2：pandas.Series.shift
    # shift用于移动数据，但是保持索引不变
    # 见识一下shift做了什么事情
# 使用pd.concat合并Series列表变成一个大的df
    ss = pd.concat(
        [df["bWendu"],
         df["bWendu"].shift(periods=1),
         df["bWendu"].shift(periods=12)],
        axis=1
    )
    # 环比
    series_shift1 = df["bWendu"].shift(periods=1)
    df["bWendu_way2_huanbi"] = (df["bWendu"]-series_shift1)/series_shift1

    # 同比
    series_shift2 = df["bWendu"].shift(periods=12)
    df["bWendu_way2_tongbi"] = (df["bWendu"]-series_shift2)/series_shift2
    print(ss.head())

    # 方法3. pandas.Series.diff
    pd.concat(
        [df["bWendu"],
         df["bWendu"].diff(periods=1),
         df["bWendu"].diff(periods=12)],
        axis=1
    ).head(15)
    # 环比
    series_diff1 = df["bWendu"].diff(periods=1)
    df["bWendu_way3_huanbi"] = series_diff1/(df["bWendu"]-series_diff1)

    # 同比
    series_diff2 = df["bWendu"].diff(periods=12)
    df["bWendu_way3_tongbi"] = series_diff2/(df["bWendu"]-series_diff2)
    print(df.head(15))
if __name__ == '__main__':
    cal_huanbi()